<template>
  <div id="panel">
    <!-- 搜索表单区域 -->
    <el-card class="queryForm">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        :label-position="'right'"
      >
        <el-form-item label="预案名称：" prop="planName">
          <el-input
            v-model="queryParams.planName"
            placeholder="请输入预案名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="预案级别：" prop="planLevel">
          <el-select
            v-model="queryParams.planLevel"
            placeholder="请选择预案级别"
          >
            <el-option label="区县" value="区县"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预案类别：" prop="planType">
          <el-select
            v-model="queryParams.planType"
            placeholder="请选择预案类别"
          >
            <el-option label="地质灾害" value="地质灾害"></el-option>
            <el-option label="防汛抗旱" value="防汛抗旱"></el-option>
            <el-option label="森林防火" value="森林防火"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布单位：" prop="publishUnit">
          <el-input
            v-model="queryParams.publishUnit"
            placeholder="请输入发布单位"
          ></el-input>
        </el-form-item>
        <el-form-item label="发布时间：" prop="publishTime">
          <el-date-picker
            v-model="queryParams.publishTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="行政区划：" prop="administrativeRegion">
          <el-select
            v-model="queryParams.administrativeRegion"
            placeholder="请选择行政区划"
          >
            <el-option label="高平市区" value="高平市区"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备案时间：" prop="recordTime">
          <el-date-picker
            v-model="queryParams.recordTime"
            type="date"
            placeholder="选择备案时间"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <div class="searchBtnBox">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button @click="resetQuery">重置</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 操作按钮和表格区域 -->
    <el-card class="pageContent">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleUpdate"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            >导出</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="tableData"
        stripe
        :height="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="planName" label="预案名称" />
        <el-table-column prop="planType" label="预案类别" />
        <el-table-column prop="planLevel" label="预案级别" />
        <el-table-column prop="administrativeRegion" label="行政区划" />
        <el-table-column prop="publishUnit" label="发布单位" />
        <el-table-column prop="publishTime" label="发布时间" />
        <el-table-column prop="recordTime" label="备案时间" />
        <el-table-column prop="inputUnit" label="录入单位" />
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="view(scope.row)">详情</el-button>
            <el-button type="text" @click="edit(scope.row)">修改</el-button>
            <el-button type="text" @click="delRows(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination-self"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :pager-count="5"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="slot, total, sizes, prev, pager, next, jumper"
        :total="tableList.total"
      >
        <el-button
          class="refresh-button"
          icon="el-icon-refresh"
          title="刷新"
          @click="getList"
        />
      </el-pagination>
    </el-card>

    <!-- 新增/修改弹框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预案名称" prop="planName" required>
              <el-input v-model="form.planName" placeholder="请输入预案名称" />
            </el-form-item>
            <el-form-item label="预案类别" prop="planType" required>
              <el-select v-model="form.planType" placeholder="请选择预案类别">
                <el-option label="地质灾害" value="地质灾害"></el-option>
                <el-option label="防汛抗旱" value="防汛抗旱"></el-option>
                <el-option label="森林防火" value="森林防火"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="录入单位" prop="inputUnit" required>
              <el-input v-model="form.inputUnit" placeholder="请输入录入单位" />
            </el-form-item>
            <el-form-item label="发布时间" prop="publishTime" required>
              <el-date-picker
                v-model="form.publishTime"
                type="date"
                placeholder="选择发布时间"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行政区划" prop="administrativeRegion" required>
              <el-select
                v-model="form.administrativeRegion"
                placeholder="请选择行政区划"
              >
                <el-option label="高平市区" value="高平市区"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预案级别" prop="planLevel" required>
              <el-select v-model="form.planLevel" placeholder="请选择预案级别">
                <el-option label="区县" value="区县"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发布单位" prop="publishUnit" required>
              <el-input
                v-model="form.publishUnit"
                placeholder="请输入发布单位"
              />
            </el-form-item>
            <el-form-item label="备案时间" prop="recordTime" required>
              <el-date-picker
                v-model="form.recordTime"
                type="date"
                placeholder="选择备案时间"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="预案文本" prop="planFile">
          <el-upload
            action="/api/upload"
            :limit="1"
            accept=".doc,.docx,.pdf"
            :file-size="50 * 1024 * 1024"
            :on-error="handleUploadError"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :show-file-list="true"
            class="upload-demo"
          >
            <el-button size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">
              请上传大小不超过50MB、格式为doc/pdf的文件
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "EmergencyPlan",
  components: {},
  data() {
    return {
      tableHeight: window.innerHeight - 400,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planName: "",
        planLevel: "",
        planType: "",
        publishUnit: "",
        publishTime: [],
        administrativeRegion: "",
        recordTime: "",
      },
      tableList: {
        total: 0,
        rows: [],
      },
      ids: [], // 存储勾选的ID集合
      tableData: [
        {
          planId: "1", // 新增唯一标识，用于删除确认
          planName: "高平市人民政府突发地质灾害总体应急",
          planType: "地质灾害",
          planLevel: "区县",
          administrativeRegion: "高平市区",
          publishUnit: "高平市",
          publishTime: "2025-02-20",
          recordTime: "2025-02-20",
          inputUnit: "高平市自然资源局",
        },
        {
          planId: "2",
          planName: "高平市防汛抗旱突发事件应急",
          planType: "防汛抗旱",
          planLevel: "区县",
          administrativeRegion: "高平市区",
          publishUnit: "高平市",
          publishTime: "2025-02-15",
          recordTime: "2025-02-15",
          inputUnit: "高平市水利局",
        },
        {
          planId: "3",
          planName: "高平市森林火灾应急预案",
          planType: "森林防火",
          planLevel: "区县",
          administrativeRegion: "高平市区",
          publishUnit: "高平市",
          publishTime: "2025-02-10",
          recordTime: "2025-02-10",
          inputUnit: "高平市林业局",
        },
      ],
      open: false,
      title: "",
      form: {
        planName: "",
        planType: "",
        inputUnit: "",
        publishTime: "",
        administrativeRegion: "",
        planLevel: "",
        publishUnit: "",
        recordTime: "",
        planFile: "",
      },
      rules: {
        planName: [
          { required: true, message: "预案名称不能为空", trigger: "blur" },
        ],
        planType: [
          { required: true, message: "预案类别不能为空", trigger: "change" },
        ],
        inputUnit: [
          { required: true, message: "录入单位不能为空", trigger: "blur" },
        ],
        publishTime: [
          { required: true, message: "发布时间不能为空", trigger: "change" },
        ],
        administrativeRegion: [
          { required: true, message: "行政区划不能为空", trigger: "change" },
        ],
        planLevel: [
          { required: true, message: "预案级别不能为空", trigger: "change" },
        ],
        publishUnit: [
          { required: true, message: "发布单位不能为空", trigger: "blur" },
        ],
        recordTime: [
          { required: true, message: "备案时间不能为空", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.pageInit();
  },
  methods: {
    pageInit() {
      this.getList();
    },
    // 监听表格勾选事件，更新ids数组
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.planId);
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加高平市应急备案";
    },
    handleUpdate() {
      // 修改操作也增加勾选判断
      if (this.ids.length === 0) {
        this.$message.warning("请先勾选需要修改的数据");
        return;
      }
      if (this.ids.length > 1) {
        this.$message.warning("只能选择一条数据进行修改");
        return;
      }
      // 获取勾选的单条数据
      const row = this.tableData.find((item) => item.planId === this.ids[0]);
      this.reset();
      this.open = true;
      this.title = "修改高平市应急备案";
      this.form = { ...row };
    },
    handleDelete() {
      // 多选删除核心判断：未勾选数据时提示
      if (this.ids.length === 0) {
        this.$message.warning("请先勾选需要删除的数据");
        return;
      }
      // 获取勾选的预案名称，用于确认提示
      const planNames = this.tableData
        .filter((item) => this.ids.includes(item.planId))
        .map((item) => item.planName)
        .join("、");

      this.$confirm(`是否确认删除以下预案：${planNames}`, "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true, // 支持显示换行
      })
        .then(() => {
          // 模拟删除接口调用
          this.tableData = this.tableData.filter(
            (item) => !this.ids.includes(item.planId)
          );
          this.ids = []; // 清空勾选
          this.getList(); // 刷新表格
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },
    view(row) {
      console.log("查看详情", row);
    },
    edit(row) {
      this.reset();
      this.open = true;
      this.title = "修改高平市应急备案";
      this.form = { ...row };
    },
    delRows(row) {
      this.$confirm(`是否确认删除预案：${row.planName}`, "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableData = this.tableData.filter(
            (item) => item.planId !== row.planId
          );
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.getList();
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        planId: "",
        planName: "",
        planType: "",
        inputUnit: "",
        publishTime: "",
        administrativeRegion: "",
        planLevel: "",
        publishUnit: "",
        recordTime: "",
        planFile: "",
      };
      this.$refs.form && this.$refs.form.resetFields();
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.open = false;
          this.$message.success(this.form.planId ? "修改成功" : "新增成功");
          this.getList();
        }
      });
    },
    handleExport() {
      this.$message.success("导出功能待实现");
    },
    getList() {
      this.tableList.total = this.tableData.length;
      this.tableList.rows = this.tableData;
    },
    beforeUpload(file) {
      const isDoc =
        file.type === "application/msword" ||
        file.type ===
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      const isPdf = file.type === "application/pdf";
      const isSize = file.size / 1024 / 1024 <= 50;
      if (!isDoc && !isPdf) {
        this.$message.error("仅支持上传 doc/docx/pdf 格式的文件");
        return false;
      }
      if (!isSize) {
        this.$message.error("文件大小不能超过 50MB");
        return false;
      }
      return true;
    },
    handleUploadSuccess(response, file) {
      this.form.planFile = response.filePath;
      this.$message.success("文件上传成功");
    },
    handleUploadError() {
      this.$message.error("文件上传失败，请重试");
    },
  },
};
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
p {
  margin: 0;
}

img {
  vertical-align: middle;
}

#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    .el-form-item {
      margin: 10px 0 10px 20px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .times {
      .el-form-item__content {
        width: 250px;
      }
    }

    .el-form-item__content {
      min-width: 200px;
    }

    .searchBtnBox {
      display: inline-block;
      margin: 10px 0 10px 20px;
    }
  }

  .pageContent {
    .tabs-list {
      padding-top: 20px;
    }

    .el-tabs__header {
      background: #fff;
    }

    .el-tabs__item {
      border: 1px solid #eee;
      margin: 0;
      border-left: 0;
      background: #fafbfc;
      color: #000;
    }

    .el-tabs__item:first-child {
      margin-left: 20px;
      border-left: 1px solid #eee;
    }

    .is-active {
      border-bottom: 0 !important;
      background: #fff;
      color: #307eff;
    }
  }

  .anjian label {
    padding: 0 !important;
    width: 100px !important;
  }

  .queryForm .el-checkbox {
    margin-right: 10px !important;
    width: auto !important;
  }

  .iszgfc .el-form-item__content {
    width: 120px;
  }
}
</style>
